package com.it.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import java.util.Objects;

@Slf4j
@Component
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final String USER_NAME = "admin"; // 用户名
    private static final String USER_PASSWORD = "123456"; //密码
    private final SAAJInInterceptor interceptor = new SAAJInInterceptor(); // 创建拦截器

    public WebServiceAuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        super.getAfter().add(SAAJInInterceptor.class.getName()); // 添加拦截器
    }


    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        // 获取指定信息
        SOAPMessage soapMessage = message.getContent(SOAPMessage.class);
        if (soapMessage == null) { // 没有消息
            this.interceptor.handleMessage(message); // 走默认流程
            soapMessage = message.getContent(SOAPMessage.class); // 再次获取消息
        }
        SOAPHeader header = null; // SOAP头信息
        try {
            header = soapMessage.getSOAPHeader();
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        if (header == null) { // 没有头信息
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        // 解析XML文档（SOAP是XML结构的）
        NodeList usernameList = header.getElementsByTagName("username");
        NodeList passwordList = header.getElementsByTagName("password");
        if (usernameList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        if (passwordList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        String username = usernameList.item(0).getTextContent().trim(); // 获取用户名
        String password = passwordList.item(0).getTextContent().trim(); // 获取密码

        if (Objects.equals(USER_NAME, username) && Objects.equals(USER_PASSWORD, password)) {
            log.info("用户访问成功");
        } else {
            SOAPException soapException = new SOAPException("用户认证失败");
            log.error("用户认证失败");
            throw new Fault(soapException);
        }
    }
}
